#! /bin/bash
. ./logger.sh
target_container=("poste" mail)
docker_u="$1"
docker_p="$2"

temp_result=1

# dockerhub login
docker_login() {
  local result=1
  if [[ $(docker login | grep  -c 'Succeeded') -eq 0 ]]; then
    info "DockerHub is not logged in or the login information has expired."
    info "User ${docker_u} login is in process."
    login_response=$(docker login -u "$docker_u" --password-stdin "$docker_p")
    if [[ "$login_response" =~ 'Login Succeeded' ]]; then
      info "Login success"
      temp_result=0
    else
      error "Login failed, response:"
      error "$login_response"
      exit 1
    fi
  else
    info "The machine has been logged into DockerHub"
    temp_result=0
  fi
}

in_target() {
  echo "${target_container[@]}" | grep -wq "$1" && echo 0 || echo 1
}

function bak() {
  info "Create image for $1 ... ..."
  image_name="$docker_u"/backup:"$1"_backup_"$(date '+%Y.%m.%d')"
  echo "$image_name"
  docker commit -a "baldwin_bak" -m "backup for $1 $(date "+%D")" "$1" "$image_name"
  info "Create image for $1 successfully, named $image_name"
  info "Push image $image_name ... ..."
  docker push "$image_name"
  info "Push image $image_name successfully"
  info "Delete local image $image_name ... ..."
  docker rmi "$image_name"
  info "Delete local image $image_name successfully, end"
}

docker_login

if [[ "$temp_result" -eq 0 ]]; then
  docker ps | while read -r line
  do
    contain_name=$(echo "$line" | awk '{print $NF}')
    if [[ $(in_target "$contain_name") = 0 ]]; then
      bak "$contain_name"
    fi
  done
    exit 0
fi